<?php

namespace app\admin\logic;

use app\common\model\DealerStatistics;
use support\Cache;
use think\facade\Db;

/**
 * 经销商统计逻辑层
 */
class DealerStatisticsLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DealerStatistics();
    }

    /**
     * 获取每天每个企业的统计汇总数据
     * @param array $where
     * @param int $limit
     * @return array
     * @throws DbException
     */
    public function getDailyCompanySummary(array $where = [], int $page = 1, int $limit = 20): array
    {
        $data = $this->model->with(['company' => function ($query) {
            $query->visible(['id', 'name']);
        }, 'dealer' => function ($query) {
            $query->visible(['id', 'name']);
        }])
            ->whereNull('delete_time')
            ->when(!empty($where), function ($query) use ($where) {
                foreach ($where as $condition) {
                    $query->where(...$condition);
                }
            })
            ->group(['stat_date', 'company_id'])
            ->field([
                'stat_date',
                'company_id',
                'error_message',
                'SUM(outbound_value) as total_outbound_value',
                'SUM(receivable_total) as total_receivable',
                'SUM(actual_total) as total_actual',
                'SUM(prepaid_service_fee) as total_prepaid_fee',
                'SUM(actual_service_fee) as total_actual_fee',
                '(SUM(prepaid_service_fee) - SUM(actual_service_fee)) as service_fee_difference'
            ])
            ->order('stat_date desc')
            ->paginate(['page' => $page, 'list_rows' => $limit]);

        $totalSummary = $this->model->whereNull('delete_time')
            ->when(!empty($where), function ($query) use ($where) {
                foreach ($where as $condition) {
                    $query->where(...$condition);
                }
            })
            ->field([
                'SUM(outbound_value) as total_outbound_value',
                'SUM(receivable_total) as total_receivable',
                'SUM(actual_total) as total_actual',
                'SUM(prepaid_service_fee) as total_prepaid_fee',
                'SUM(actual_service_fee) as total_actual_fee',
                'SUM(prepaid_service_fee - actual_service_fee) as service_fee_difference'
            ])
            ->select()->toArray();
        
        $list = $data->toArray();
        $list['summary'] = array_merge([
            'stat_date' => '合计'
        ], $totalSummary[0] ?? []);
        return $list;
    }

    /**
     * 获取指定企业下所有经销商的数据
     * @param array $where
     * @return array
     */
    public function getDealersByCompany(array $where = [], int $page = 1, int $limit = 20): array
    {
        $results = $this->model->with(['company' => function ($query) {
            $query->visible(['id', 'name']);
        }, 'dealer' => function ($query) {
            $query->visible(['id', 'name']);
        }])
            ->where($where)
            ->whereNull('delete_time')
            ->field([
                '*',
                'prepaid_service_fee - actual_service_fee as service_fee_difference'
            ])
            ->paginate(['page' => $page, 'list_rows' => $limit]);

        $summary = $this->model->where($where)
            ->whereNull('delete_time')
            ->field([
                'SUM(outbound_value) as outbound_value',
                'SUM(receivable_total) as receivable_total',
                'SUM(actual_total) as actual_total',
                'SUM(prepaid_service_fee) as prepaid_service_fee',
                'SUM(actual_service_fee) as actual_service_fee',
                'SUM(prepaid_service_fee - actual_service_fee) as service_fee_difference'
            ])
            ->select()->toArray();

        $list = $results->toArray();
        $list['summary'] = array_merge([
            'dealer' => ['name' => '合计']
        ], $summary[0] ?? []);
        return $list;
    }

    /**
     * @param $date
     * @param $companyId
     * @param $dealerId
     * @param $data
     * @return DealerStatistics|array|bool|\think\Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveOrUpdate($date, $companyId, $dealerId, $data): DealerStatistics|bool|array|\think\Model
    {
        // 查询数据是否存在
        $record = $this->model->where('stat_date', $date)
            ->where('company_id', $companyId)
            ->where('dealer_id', $dealerId)
            ->find();

        if ($record) {
            // 数据存在，则更新并累加指定字段
            $updateData = [
                'outbound_value' => Db::raw('outbound_value + ' . floatval($data['outbound_value'])),
                'receivable_total' => Db::raw('receivable_total + ' . floatval($data['receivable_total'])),
                'prepaid_service_fee' => Db::raw('prepaid_service_fee + ' . floatval($data['prepaid_service_fee'])),
                'update_time' => time(),
            ];

            if (!empty($data['actual_total'])) {
                $updateData['actual_total'] = Db::raw('actual_total + ' . floatval($data['actual_total']));
            }

            return $record->where('id', $record['id'])
                ->update($updateData);
        } else {
            // 数据不存在，则插入
            $data['stat_date'] = $date;
            $data['company_id'] = $companyId;
            $data['dealer_id'] = $dealerId;
            $data['create_time'] = time();

            return $this->model->create($data);
        }
    }

}
